﻿using System;
using System.Text.RegularExpressions;
using WorkItemAnalyser.Core.Assertions;

namespace WorkItemAnalyser.Core.Parsers
{
    public class TextLinkAssertionParser : IAssertionParser
    {
        const string RuleGrammer = @"(?<linkCount>\d*) (?<linkType>\w*) links? to a (?<workItemType>.*)";
        
        public IAssertion ParseAssertion(string assertionText)
        {
            const string requiredPrefix = "must have";
            const string looseMatchPrefix = requiredPrefix + " at least ";
            bool matchExact = true;

            if (!assertionText.StartsWith(requiredPrefix, StringComparison.OrdinalIgnoreCase))
                return null;

            if (assertionText.StartsWith(looseMatchPrefix, StringComparison.OrdinalIgnoreCase))
                matchExact = false;

            assertionText = assertionText.TrimStart(looseMatchPrefix.ToCharArray());
           
            var ruleExpression = new Regex(RuleGrammer);
            var matches = ruleExpression.Match(assertionText);

            if (!matches.Success)
                return null;

            var count = int.Parse(matches.Groups["linkCount"].ToString());
            var type = matches.Groups["linkType"].ToString();
            var workItemType = matches.Groups["workItemType"].ToString();

            if (count < 0 || string.IsNullOrWhiteSpace(type) || string.IsNullOrWhiteSpace(workItemType))
                return null;

            return new LinkAssertion(workItemType, count, type, matchExact);
        }
    }
}